package com.test;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @Description TODO(这里用一句话描述这个类的作用)
 *
 * @author liuqinghua
 * @date 2025-8-28
 */
import javax.imageio.ImageIO;

public class ImageResizer {
    public static void resizeImageWithQuality(File inputFile, File outputFile, int newWidth) throws IOException {
        BufferedImage originalImage = ImageIO.read(inputFile);
        int sWidth = originalImage.getWidth();
        int sHeight = originalImage.getHeight();
        int picWidth = newWidth;
        BigDecimal rate = new BigDecimal(picWidth).divide(new BigDecimal(sWidth), 2, BigDecimal.ROUND_HALF_UP);
        int width = newWidth;
        int height = new BigDecimal(sHeight).multiply(rate).setScale(0, BigDecimal.ROUND_HALF_DOWN).intValue();
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // 使用高质量插值方法
        g2d.drawImage(originalImage, 0, 0, width, height, null);
        g2d.dispose();
        ImageIO.write(resizedImage, "jpg", outputFile); // 可以更换为"png"等格式
    }

    public static void main(String[] args) {
        try {
            File input = new File("D:/img/222.jpg");
            File output = new File("D:/img/222-1.png");
            resizeImageWithQuality(input, output, 240); // 调整为800x600像素并保持高质量
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}